﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using System.Collections;
using System.DirectoryServices;

namespace DataAccess.Operate
{
    public class DA_Employee_Inherit : SqlInteractionBase
    {
        #region 变量定义（域用户登录设置）
        private string[] sUser = { "zhangjb", "bin0.." }; //域用户登录
        #endregion

        #region 根据姓名取当前用户的Email
        /// <summary>
        /// 根据姓名取当前用户的Email
        /// </summary>
        /// <returns></returns>
        private string getUserEmail(string sName)
        {
            string sSql = "select EMail from [gzs-fin02].AIS20050623105602.dbo.HM_Employees " +
                    "where Name='" + sName + "'";
            SqlCommand cmdToExecute = new SqlCommand();
            SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute);
            DataSet ds = new DataSet();

            cmdToExecute.CommandText = sSql;
            cmdToExecute.CommandType = CommandType.Text;

            try
            {
                cmdToExecute.Connection = _mainConnection;
                if (_mainConnectionIsCreatedLocal)
                {
                    _mainConnection.Open();
                }
                else
                {
                    if (_mainConnectionProvider.IsTransactionPending)
                    {
                        cmdToExecute.Transaction = _mainConnectionProvider.CurrentTransaction;
                    }
                }

                adapter.Fill(ds);

            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message.ToString());
            }
            finally
            {
                if (_mainConnectionIsCreatedLocal)
                {
                    _mainConnection.Close();
                }

                cmdToExecute.Dispose();

                adapter.Dispose();
            }

            if (ds.Tables[0].Rows.Count > 0)
            {
                return ds.Tables[0].Rows[0]["EMail"].ToString();
            }
            else
            { return ""; }
        }
        #endregion

        #region 获取邮箱（先从域用户中查找用户邮箱，如果没有，再从K3查找）
        /// <summary>
        /// 获取邮箱（先从域用户中查找用户邮箱，如果没有，再从K3查找）
        /// </summary>
        /// <returns></returns>
        public string getDomainUserEmail(string username, bool showEX)
        {
            string email = "";
            try
            {
                if (username != "")
                {
                    string ADPath = "LDAP:// CENTALINE";

                    using (DirectoryEntry root = new DirectoryEntry(ADPath, sUser[0], sUser[1], AuthenticationTypes.Secure))
                    {
                        DirectorySearcher ds = new DirectorySearcher(root);
                        ds.Filter = "(&(objectClass=user)(Name=" + username + "))";
                        ds.PropertiesToLoad.Add("description");
                        ds.PropertiesToLoad.Add("memberOf");

                        foreach (SearchResult res in ds.FindAll())
                        {
                            if (null != res)
                            {
                                if ((res.Properties["description"][0]).ToString().Trim().Substring(0, 2) == "AD" && (res.Properties["memberOf"][0]).ToString().Contains("广州"))
                                {
                                    email = res.GetDirectoryEntry().Properties["mail"].Value.ToString();
                                    break;
                                }
                            }
                        }
                    }
                    if (string.IsNullOrEmpty(email))
                    {
                        email = getUserEmail(username);
                    }
                }
                return email;

            }
            catch (Exception ex)
            {
                if (showEX)
                {
                    throw new Exception(ex.Message);
                }
                else
                {
                    return getUserEmail(username);
                }
            }

        }
        #endregion
    }
}
